<?php
/**
 * Created by PhpStorm.
 * User: PhpZhi
 * Date: 2019/11/6 21:28
 * Note: 微信类
 */

namespace app\api\controller\user;


use app\common\controller\Api;
use app\common\model\wechat\WechatUser;
use app\common\model\user as UserModel;
use think\Cache;
use think\Exception;
use zhi\MiniProgram;

class Wechat extends Api
{
    protected $noNeedLogin = ['login'];

    public function login()
    {
        $data = $this->request->post();
        $code = $this->request->post('code');
        $cache_key = $this->request->post('cache_key') ?: '';
        $login_type = $this->request->post('login_type') ?: '';

        $session_key = Cache::get('zhi_api_code_' . $cache_key);
        if (!$code && !$session_key)
            $this->error('授权失败，参数不正确');

        // 获取 session_key
        if ($code && !$session_key) {
            try {
                $authInfo = MiniProgram::getUserInfo($code);
                $session_key = $authInfo['session_key'];
                $cache_key = md5(time() . $code);
                Cache::set('zhi_api_code_' . $cache_key, $session_key, 86400);
            } catch (Exception $e) {
                $this->error('获取session_key失败，请检查您的配置！', [
                    'line' => $e->getLine(),
                    'message' => $e->getMessage()
                ]);
            }
        }

        list($spread_id, $spread_code, $iv, $encryptedData) = [
            $data['spread_id'] ?: 0,
            $data['spread_code'] ?: '',
            $data['iv'] ?: '',
            $data['encryptedData'] ?: ''
        ];
        try {
            // 获取加密信息
            $wechatUser = MiniProgram::encryptor($session_key, $iv, $encryptedData);
        } catch (Exception $e) {
            if ($e->getCode() === '-41003') $this->error('获取会话密钥失败');
        }
        if (!isset($wechatUser['openId'])) $this->error('openid获取失败，请检查您的配置');
        if (!isset($wechatUser['unionId'])) $wechatUser['unionId'] = '';

        // 推广人id
        $wechatUser['spread_id'] = $spread_id;
        $wechatUser['spread_code'] = $spread_code;
        $wechatUser['session_key'] = $session_key;
        $wechatUser['login_type'] = $login_type;

        // 保存或更新授权信息到微信用户表
        $userId = WechatUser::saveWechatUserInfo($wechatUser);
        $this->auth->keeptime(86400);

        $userInfo = \app\common\model\User::where('id', $userId)->find();
        if ($userInfo['login_type'] == 'h5' && ($h5userInfo = UserModel::where(['username' => $userInfo['phone'], 'phone' => $userInfo['phone'], 'user_type' => 'h5'])->find())) {
            $this->success(__('Logged in successful'), [
                'data' => $this->auth->getUserinfo(),
                'expired_time' => time() + 86400,
                'cache_key' => $cache_key
            ]);
        }
        $this->success(__('Logged in successful'), [
            'data' => $this->auth->getUserinfo(),
            'expired_time' => time() + 86400,
            'cache_key' => $cache_key
        ]);
    }
}